<template>
  <view class="container">

    <!-- 评论弹窗 -->
    <view v-if="showComment" class="comment-modal">
      <!-- 遮罩层 -->
      <view class="mask" @click="closeCommentPanel"></view>

      <!-- 评论主体 -->
      <view class="comment-main" :style="{ height: panelHeight + 'px' }">
        <!-- 标题栏 -->
        <view class="header">
          <text class="title">{{ currentReply ? '回复 @' + currentReply.nickName : '全部评论' }}</text>
          <text class="close" @click="closeCommentPanel">×</text>
        </view>

        <view class="notice" @click="goNotice">
          <view style="flex-direction: row;align-items: center">
            <image class="img" src="../../static/player/notic.png" lazy-load></image>
            <text style="margin: 0 10rpx;font-size: 26rpx">|</text>
            <u-notice-bar :text="activity.title" :icon="false" style="width: 500rpx;" fontSize="26" color="#000000" bgColor="#ffffff" speed="60" duration="1500"></u-notice-bar>
<!--            <text style="font-size: 26rpx">发评论赚金币，1.5亿超大金币奖池!</text>-->
          </view>
          <image style="width: 30rpx;height: 30rpx;" src="../../static/player/rightBlack.png" lazy-load></image>
        </view>

        <!-- 评论列表 -->
        <list class="comment-list" ref="list" loadmoreoffset="50" @loadmore="getData">
          <cell v-for="(comment, index) in comments" :key="comment.id">
            <!-- 主评论项 -->
            <view class="comment-item">
              <u-avatar :src="comment.avatar" style="margin-right: 12rpx;" size="80"/>

              <view class="content">
                <!-- 用户信息 -->
                <text class="username">{{ comment.nickName }}</text>

                <!-- 评论内容 -->
                <text class="text">{{ comment.content }}</text>

                <!-- 操作栏 -->
                <view class="action-bar">
                  <text class="time">{{ getDateTimeFormat(comment.createTime) }}</text>
                  <text class="reply-btn" @click="handleReply(comment)" v-if="comment.userId !== userInfo.userId">回复</text>
<!--                  <view class="like-btn" @click="toggleLike(comment)">-->
<!--                    <image src="/static/player/aixinRed.png" v-if="comment.liked" style="width: 26rpx;height: 26rpx;" lazy-load></image>-->
<!--                    <image src="/static/player/aixin.png" v-else style="width: 26rpx;height: 26rpx;" lazy-load></image>-->
<!--                    <text class="count">{{ comment.likes}}</text>-->
<!--                  </view>-->
                </view>

                <!-- 子回复列表 -->
                <view class="reply-list" v-if="comment.total > 0">

                  <view v-for="reply in visibleReplies(comment)" :key="reply.id" class="reply-item">
                    <u-avatar :src="comment.avatar" style="margin-right: 12rpx;" size="80"/>
                    <view>
                      <view style="flex-direction: row">
                        <text class="reply-user">{{ reply.nickName }}</text>
                        <text class="reply-to" v-if="reply.parentNickName">@{{ reply.parentNickName }}</text>
                      </view>
                      <text class="reply-text">{{ reply.content }}</text>
                      <view class="action-bar">
                        <text class="time">{{ getDateTimeFormat(reply.createTime) }}</text>
                        <text class="reply-btn" @click="handleReply(reply)" v-if="reply.userId !== userInfo.userId">回复</text>
<!--                        <view class="like-btn" style="margin-left: 250rpx" @click="toggleLike(reply)">-->
<!--                          <image src="/static/player/aixinRed.png" v-if="reply.liked" style="width: 26rpx;height: 26rpx;" lazy-load></image>-->
<!--                          <image src="/static/player/aixin.png" v-else style="width: 26rpx;height: 26rpx;" lazy-load></image>-->
<!--                          <text class="count">{{ reply.likes}}</text>-->
<!--                        </view>-->
                      </view>
                    </view>
                  </view>

                  <!-- 折叠控制 -->
                  <view class="fold-control">
                    <text @click="toggleReplies(comment, true)" v-if="!comment.showReplies" class="unfold">展开{{ comment.total }}条评论 ▼</text>
                    <view style="flex-direction: row" v-else>
                      <text class="unfold" v-if="comment.replies.length > 2 && !comment.status" @click="getMore(comment)">展开更多</text>
                      <text style="margin-left: 30rpx" class="unfold" @click="toggleReplies(comment, false)">收起回复 ▲</text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </cell>
        </list>

        <!-- 输入区域 -->
        <view class="input-area" :style="{height: `${inputHeight}rpx`}">
          <view  class="send-msg" :style="{bottom:`${keyboardHeight}rpx`}">
            <input class="comment-input"
                   confirm-type="send"
                   type="text"
                   ref="input"
                   v-model="inputText"
                   :placeholder="inputPlaceholder"
                   @confirm="sendComment"
                   :focus="autoFocus"
                   :adjust-position="false"
                   placeholder-class="placeholder"/>
            <text class="send-btn" @click="sendComment">发送</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>
<script>

import {Api} from "../service/api";
import {getDateTimeFormat} from "../utils/formatTime";
import {gotoPage, rpxToPx} from "../utils/common";

export default {
  data() {
    return {
      showComment: false,
      autoFocus: false,
      inputText: '',
      currentReply: null,
      panelHeight: 600,
      pageObj: {
        pageSize: 10,
        pageNum: 0,
        status: 'loading'
      },
      comments: [],
      keyboardHeight: 0, // 键盘高度
      bottomHeight: 0, // 发送框高度
      activity: {}, // 评论活动信息
    }
  },
  props: {
    userInfo: {
      type: Object,
      default: {}
    },
    tvId: {
      type: Number,
      default: 0
    }
  },
  computed: {
    totalComments() {
      return this.comments.reduce((sum, c) => sum + 1 + c.replies.length, 0)
    },
    inputPlaceholder() {
      return this.currentReply ? `回复 @${this.currentReply.nickName}` : '善于结善缘，恶语伤人心'
    },
    // 发送框高度 + 键盘弹起来的高度
    inputHeight(){
      return this.bottomHeight + this.keyboardHeight + 50;
    },
  },

  mounted(){
    this.getData()

    uni.onKeyboardHeightChange(res => {
      this.keyboardHeight = rpxToPx(res.height);
      if(this.keyboardHeight<=0) {
        this.keyboardHeight = 0;
      }
    });

    this.getActivity()
  },

  methods: {
    getDateTimeFormat,
    getData(){
      if(this.pageObj.status === 'nomore') return
      this.pageObj.status = 'loading'
      Api.commentPage({
        tvId: this.tvId,
        pageNo: ++ this.pageObj.pageNum,
        pageSize: this.pageObj.pageSize,
      }).then(res=>{
        this.comments = this.comments.concat(res.data.list)
        if(this.list.length < res.data.total)  this.pageObj.status = 'loadmore'
        else this.pageObj.status = 'nomore'
      })
    },

    getMore(item){
      const page = item.page || 1
      Api.commentParentPage({
        page: page,
        parent: item.id,
        tvId: this.tvId
      }).then(res=>{
        item.replies = [...item.replies, ...res.data.map(val => {
          return {
            id: val.id,
            nickName: val.nickName,
            avatar: val.avatar,
            content: val.content,
            likes: val.likes,
            liked: val.liked,
            createTime: val.createTime,
            parentNickName: val.parentNickName,
            parentAvatar: val.parentNickName,
            userId: val.userId
          }
        })]
        item.page = page + 1
        if(res.data.length < 3) item.status = 'nomore'
        this.comments = [...[], ...this.comments]
        console.log(this.comments)
      })
    },

    getActivity(){
      Api.activity(1).then(res =>{
        this.activity = res.data
      })
    },

    // 显示评论面板
    showCommentPanel() {
      this.showComment = true
      this.calculatePanelHeight()
      // this.$nextTick(() => {
      //   this.autoFocus = true
      // })
    },

    // 关闭面板
    closeCommentPanel() {
      this.showComment = false
      this.currentReply = null
      this.inputText = ''
    },

    // 计算面板高度
    calculatePanelHeight() {
      const { windowHeight } = uni.getSystemInfoSync()
      this.panelHeight = windowHeight * 0.72
    },

    // 获取可见回复
    visibleReplies(comment) {
      return comment.showReplies ? comment.replies : []
    },

    // 切换回复展开
    toggleReplies(comment,flag) {
      if(flag) this.getMore(comment)
      comment.showReplies = !comment.showReplies
    },

    // 点赞处理
    toggleLike(comment) {
      comment.liked = !comment.liked
      comment.likes += comment.liked ? 1 : -1
      this.comments = [...[], ...this.comments]
      // 这里调用接口同步到后端
    },

    // 处理回复
    handleReply(target) {
      // console.log(target)
      this.currentReply = target
      this.$nextTick(() => {
        this.$refs.input.focus()
        // this.scrollToTarget()
      })
    },

    // 发送评论
    async sendComment() {
      if (!this.inputText.trim()) return
      // uni.showLoading({
      //   title: "正在加载...",
      //   mask: true // 是否显示透明蒙层，防止触摸穿透
      // });

      let data = {
        tvId: this.tvId,
        content: this.inputText.trim(),
        avatar: this.userInfo.avatar,
        nickName: this.userInfo.nickName,
        likes: 0,
        liked: false,
        createTime: Date.now(),
        parentNickName: null,
        parentAvatar: null,
        total: 0,
        userId: this.userInfo.userId
      }
	  console.log(this.currentReply);
      if(!this.currentReply){
        // 主评论
        data.parent = 0
        let res = await Api.createComment(data)
        data.topParent = res.data
        data.id = res.data
        this.comments.unshift(data)
      }else {
        // 顶级评论
        const mainComment = this.findMainComment(this.currentReply)
        if(this.currentReply.replies){
          // 二级评论
          data.parent = this.currentReply.id
          data.topParent = mainComment.id
        } else {
          // 多级评论
          data.parent = this.currentReply.id
          data.topParent = mainComment.id
          data.parentNickName = this.currentReply.nickName
        }
        let res = await Api.createComment(data)
        data.id = res.data
        mainComment.total += 1
        mainComment.replies.unshift(data)
        mainComment.showReplies = true
      }
      this.comments = [...[], ...this.comments]
      // uni.hideLoading();
      this.$emit('sendComment', data)
      this.resetInput()
      this.scrollToNewComment(data)
    },

    // 查找主评论
    findMainComment(target) {
      // 如果目标本身就是主评论
      if (this.comments.some(c => c.id === target.id)) return target

      // 查找包含该回复的主评论
      return this.comments.find(c =>
          c.replies.some(r => r.id === target.id)
      )
    },

    // 重置输入
    resetInput() {
      this.inputText = ''
      this.autoFocus = false
      this.currentReply = null
    },

    // 滚动到最新评论
    scrollToNewComment(comment) {
      this.$nextTick(() => {
        const index = this.comments.findIndex(c => c.id === comment.id)
        if (index !== -1) {
          this.$refs.list.scrollToIndex({
            index,
            animated: true,
            viewPosition: 0.2
          })
        }
      })
    },

    goNotice(){
      if(this.activity.skipType === 1){
        gotoPage(this.activity.path)
        this.$emit('skip', '1')
      }else {
        uni.navigateToMiniProgram({
          appId: this.activity.linkAppid,
          path: this.activity.path,
          success(res) {
            this.$emit('skip', '1')
            // 打开成功
            uni.showToast({
              title: '跳转成功'
            })
          },
          fail(err) {
            this.$emit('skip', '1')
            console.log(err)
            // 打开失败/取消
            uni.showToast({
              title: '跳转不成功',
            })
          }
        })
      }
    }

  }
}
</script>


<style scoped lang="scss">
/* 容器样式 */
.container {
  flex: 1;
  background-color: #000;
}

/* 评论触发按钮 */
.comment-trigger {
  position: fixed;
  right: 30rpx;
  bottom: 200rpx;
  flex-direction: row;
  align-items: center;
  background: rgba(0, 0, 0, 0.4);
  padding: 12rpx 24rpx;
  border-radius: 40rpx;
}
.icon {
  font-size: 26rpx;
  color: #AFAFAF;
}
.count {
  color: #AFAFAF;
  font-size: 26rpx;
  margin-left: 10rpx;
}

/* 评论弹窗 */
.comment-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
}

/* 遮罩层 */
.mask {
  flex: 1;
  background: rgba(0, 0, 0, 0.5);
}

/* 评论主体 */
.comment-main {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  border-top-left-radius: 24rpx;
  border-top-right-radius: 24rpx;
  padding: 32rpx 24rpx;
  transition: transform 0.3s ease;
}

/* 头部 */
.header {
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
  //border-bottom-width: 1rpx;
  //border-bottom-color: #eee;
}
.title {
  font-size: 34rpx;
  font-weight: 600;
  color: #333;
}
.close {
  font-size: 48rpx;
  color: #666;
  padding: 0 20rpx;
}

/* 评论项 */
.comment-item {
  flex-direction: row;
  padding: 32rpx 0;
  border-bottom-width: 1rpx;
  border-bottom-color: #f5f5f5;
}
.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 12rpx;
}

/* 内容区域 */
.content {
  flex: 1;
}
.username {
  font-size: 28rpx;
  color: #666;
  font-weight: bold;
  margin-right: 16rpx;
  flex-direction: row;
  align-items: center;
  margin-bottom: 4rpx;
}
.time {
  font-size: 24rpx;
  color: #999;
}
.text {
  font-size: 28rpx;
  color: #333;
  width: 580rpx;
  //min-height: 50rpx;
  //height: auto;
  //line-height: 1.5;
}

/* 操作栏 */
.action-bar {
  flex-direction: row;
  align-items: center;
  margin-top: 4rpx;
}
.like-btn {
  flex-direction: row;
  align-items: center;
  margin-left: 340rpx;
}
.like-btn .icon {
  font-size: 26rpx;
  color: #666;
  margin-right: 8rpx;
}
.like-btn .liked {
  color: #FF2C55;
}
.reply-btn {
  color: #737373;
  font-size: 26rpx;
  margin-left: 20rpx;
}

.unfold{
  color: #737373;
  font-size: 26rpx;
}

/* 子回复列表 */
.reply-list {
  margin-top: 10rpx;
  //background: #f8f8f8;
  //border-radius: 12rpx;
  //padding: 16rpx;
}
.reply-item {
  position: relative;
  padding: 12rpx 120rpx 12rpx 0;
  display: flex;
  flex-direction: row;
}
.reply-user {
  color: #B3B3B3;
  font-size: 26rpx;
}
.reply-to {
  color: #999;
  font-size: 26rpx;
  margin: 0 4rpx;
}
.reply-text {
  color: #333;
  font-size: 26rpx;
  width: 80vw;
}

/* 回复按钮 */
.reply-item .reply-btn {
  position: absolute;
  right: 16rpx;
  top: 50%;
  transform: translateY(-50%);
  color: #5870FE;
  font-size: 24rpx;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
  background: rgba(88, 112, 254, 0.1);
}

/* 折叠控制 */
.fold-control {
  padding: 8rpx 0 4rpx;
}
.fold-control text {
  color: #999;
  font-size: 24rpx;
}

/* 输入区域 */
.input-area {
  flex-direction: row;
  align-items: center;
  border-top-width: 1rpx;
  border-top-color: #eee;
  padding: 24rpx 0 env(safe-area-inset-bottom);
  width: 100vw;
}
.send-msg {
  color: #fff;
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 15rpx 0 15rpx;
  transition: all 0.1s ease;
  position: fixed;
  bottom: 0;
  left: 0;
  background: #fff;
}

.comment-input {
  width: 580rpx;
  height: 80rpx;
  padding: 0 24rpx;
  background: #f5f5f5;
  border-radius: 40rpx;
  font-size: 28rpx;
  margin-left: 40rpx;
}
.send-btn {
  color: #E81F4B;
  font-size: 28rpx;
  margin-left: 24rpx;
  transition: color 0.3s;
  font-weight: 500;
}
.placeholder {
  color: #999;
}

/* 公告区域 */
.notice{
  border: 2rpx solid #F5F5F5;
  border-radius: 20rpx;
  width: 680rpx;
  height: 80rpx;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 0 20rpx;
}

.img{
  width: 40rpx;
  height: 40rpx;
}
</style>
